<template>
  <div class="smart-creation-page">
    <div class="header">
      <h1>智能创作 - 步骤 {{ step }} / 2</h1>
      <p>当前模板 ID: {{ templateId }}</p>
    </div>

    <div v-if="loading" class="loading-state">
      <p>数据加载中，请稍候...</p>
    </div>

    <!-- 步骤 1: 选择纹理分类 -->
    <div v-if="step === 1 && !loading" class="step-content">
      <h2>1. 请选择纹理分类：</h2>
      <div v-if="textureCategories.length > 0" class="category-list">
        <div
          v-for="category in textureCategories"
          :key="category.id"
          @click="selectCategory(category)"
          :class="[
            'category-card',
            { 'is-selected': selectedCategory && selectedCategory.id === category.id },
          ]"
        >
          <h3>{{ category.name }}</h3>
          <p>{{ category.description || '点击查看该分类下的具体纹理' }}</p>
          <span
            v-if="selectedCategory && selectedCategory.id === category.id"
            class="selection-mark"
            >✅ 已选中</span
          >
        </div>
      </div>
      <div v-else>
        <p>暂无纹理分类数据。</p>
      </div>
    </div>

    <!-- 步骤 2: 选择具体纹理 -->
    <div v-if="step === 2 && !loading" class="step-content">
      <h2>2. 选择具体纹理模板 ({{ selectedCategory?.name }})：</h2>

      <div v-if="textures.length > 0" class="texture-list">
        <div
          v-for="texture in textures"
          :key="texture.id"
          @click="selectTexture(texture)"
          :class="[
            'texture-card',
            { 'is-selected': selectedTexture && selectedTexture.id === texture.id },
          ]"
        >
          <!-- 假设 TextureTemplate 对象中有一个 imagePath 字段作为预览图 -->
          <img
            :src="texture.imageUrl || '/placeholder-texture.jpg'"
            :alt="texture.name"
            class="texture-preview"
          />
          <h4>{{ texture.name }}</h4>
          <span v-if="selectedTexture && selectedTexture.id === texture.id" class="selection-mark"
            >✅ 已选中</span
          >
        </div>
      </div>
      <div v-else>
        <p>该分类下暂无纹理模板。</p>
      </div>

      <div class="actions">
        <button @click="step = 1" class="btn-back">← 返回分类选择</button>

        <button @click="continueCreation" :disabled="!selectedTexture" class="btn-next">
          继续创作 (进入编辑器) →
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// 导入新的 API 函数
import { getAllTextureCategories, getTexturesByCategory } from '@/api/creationApi'

const route = useRoute()
const router = useRouter()

// 状态变量
const templateId = ref(parseInt(route.params.id)) // 从路由获取的模板 ID
const loading = ref(true)
const step = ref(1) // 创作步骤: 1: 选分类, 2: 选纹理

// 数据模型
const textureCategories = ref([]) // 纹理分类列表 (TXTCategory)
const selectedCategory = ref(null)
const textures = ref([]) // 具体纹理模板列表 (TextureTemplate)
const selectedTexture = ref(null)

/**
 * 步骤 1: 获取所有纹理分类
 */
const fetchTextureCategories = async () => {
  loading.value = true
  try {
    const res = await getAllTextureCategories()
    // 假设 API 返回的数据在 res.data 中
    textureCategories.value = res.data
  } catch (error) {
    console.error('获取纹理分类失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 选择一个纹理分类，并进入下一步（获取该分类下的具体纹理）
 * @param {object} category - 选中的 TXTCategory 对象
 */
const selectCategory = async (category) => {
  // 检查是否重复点击，如果是，且纹理已加载，则直接进入 step 2
  if (selectedCategory.value?.id === category.id && textures.value.length > 0) {
    step.value = 2
    return
  }

  selectedCategory.value = category
  selectedTexture.value = null // 清空已选纹理
  textures.value = [] // 清空纹理列表

  loading.value = true
  try {
    // 调用带 categoryId 参数的纹理列表接口
    const res = await getTexturesByCategory(category.id)
    textures.value = res.data
    step.value = 2 // 移动到步骤 2
  } catch (error) {
    console.error(`加载分类 ${category.id} 的纹理失败:`, error)
    alert('加载纹理列表失败，请重试或返回。')
    step.value = 1 // 失败后保持在步骤 1
  } finally {
    loading.value = false
  }
}

/**
 * 步骤 2: 选择一个具体纹理
 * @param {object} texture - 选中的 TextureTemplate 对象
 */
const selectTexture = (texture) => {
  selectedTexture.value = texture
}

/**
 * 最终操作: 继续创作（导航到核心编辑器）
 */
const continueCreation = () => {
  if (!selectedTexture.value || !templateId.value) {
    alert('请确保已选择纹理并获取到模板ID！')
    // 调试：如果进入这里，说明条件不满足
    console.error('跳转失败：缺少 selectedTexture 或 templateId', {
      templateId: templateId.value,
      selectedTexture: selectedTexture.value,
    })
    return
  }

  const textureId = selectedTexture.value.id

  // 【✅ 关键调试点：打印生成的路径】
  const targetPath = `/editor/${templateId.value}/texture/${textureId}`
  console.log(`准备跳转到核心创作环节，目标路径: ${targetPath}`)

  router.push({
    path: targetPath,
  })

  // 确保没有其他阻止跳转的逻辑
}

onMounted(fetchTextureCategories)
</script>

<style scoped>
/* 样式仅为示例，请根据项目自行调整 */
.smart-creation-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: sans-serif;
}

.header {
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 30px;
}

.step-content {
  margin-top: 20px;
  padding: 25px;
  border: 1px solid #f0f0f0;
  border-radius: 10px;
  background-color: #fff;
}

.category-list,
.texture-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.category-card,
.texture-card {
  border: 2px solid #ddd;
  padding: 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  width: 200px;
  text-align: center;
  position: relative;
}

.category-card:hover,
.texture-card:hover {
  border-color: #007bff;
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.15);
}

.is-selected {
  border-color: #28a745 !important;
  background-color: #e9fbf0;
  box-shadow: 0 0 10px rgba(40, 167, 69, 0.4);
}

.selection-mark {
  position: absolute;
  top: -10px;
  right: -10px;
  background-color: #28a745;
  color: white;
  padding: 2px 8px;
  border-radius: 15px;
  font-size: 12px;
}

.texture-preview {
  height: 100%;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  background-color: #f5f5f5;
  border: 1px solid #eee;
}

.actions {
  overflow: hidden; /* 包含浮动按钮 */
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.btn-next,
.btn-back {
  padding: 5px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
}

.btn-next {
  float: right;
  background-color: #007bff;
  color: white;
}

.btn-next:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.btn-back {
  float: left;
  background-color: #6c757d;
  color: white;
}
</style>
